#!/usr/bin/env python

import webob
import os
import tempita
import threading
from onsocial import model

paths = tempita.bunch()
paths.root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir))
paths.templates = os.path.join(paths.root, "templates")

webenv = threading.local()

def wsgify(content_type='text/html',
           charset='utf-8'):
    def decorator(func):
        def app(environ, start_response):
            res = func(**webenv.request.urlvars)
            if isinstance(res, basestring):
                res = webob.Response(body=res,
                                     content_type=content_type,
                                     charset=charset)
            return res(environ, start_response)
        return app
    return decorator

def render(template_name, **vars):
    tmpl = tempita.HTMLTemplate.from_filename(os.path.join(paths.templates,
                                                           template_name))
    vars.update(request=webenv.request,
                environ=webenv.request.environ)
    return tmpl.substitute(vars)

class Middleware(object):
    def __init__(self, app, conf):
        self.app = app
        self.conf = conf
        
    def __call__(self, environ, start_response):
        req = webob.Request(environ)
        session = environ['beaker.session']
        if 'REMOTE_USER' in session:
            environ['REMOTE_USER'] = session['REMOTE_USER']
        webenv.session = session
        webenv.request = req
        try:
            return self.app(environ, start_response)
        finally:
            webenv.session.save()
            webenv.request = None
            webenv.session = None
            model.Session.remove()
